package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.validation.GroupDefinitionException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCommand;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserAccountFeignClient userAccountFeignClient;
    @Autowired
    private UserPaidTrackService userPaidTrackService;
    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Override
    @SneakyThrows
    @GlobalTransactional
    public String wxLogin(String code) {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openid = sessionInfo.getOpenid();

        //根据openid查询用户信息
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getWxOpenId, openid);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoLambdaQueryWrapper);
        if (userInfo == null) {
            //新用户注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname(System.currentTimeMillis() + "听友");
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");

            userInfoMapper.insert(userInfo);

            //todo: 初始化用户账号信息
            Result result = userAccountFeignClient.initUserAccount(userInfo.getId());
            if (result.getCode() != 200) {
                throw new GuiguException(ResultCodeEnum.USER_ACCOUNT_ERROR);
            }

        }

        //获取token
        String token = UUID.randomUUID().toString().replace("-", "");

        //将token存入redis
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(key, JSON.toJSONString(userInfo), 7, TimeUnit.DAYS);

        return token;
    }

    @Override
    public UserInfoVo getUserInfo() {
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    @Override
    public Map<Long, Integer> userIsPaidTrack(Long albumId, List<Long> stackIds) {
        Long userId = AuthContextHolder.getUserId();
        //判断是否购买过专辑
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId, userId);
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(userPaidAlbumLambdaQueryWrapper);
        Map<Long, Integer> map = new HashMap<>();
        if (userPaidAlbum != null) {
            stackIds.stream().forEach(stackId -> {
                map.put(stackId, 1);
            });
        } else {
            //判断是否购买过声音
            stackIds.stream().forEach(stackId -> {
                LambdaQueryWrapper<UserPaidTrack> LambdaQueryWrapper = new LambdaQueryWrapper<>();
                LambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId);
                LambdaQueryWrapper.eq(UserPaidTrack::getTrackId, stackId);
                UserPaidTrack paidTrack = userPaidTrackService.getOne(LambdaQueryWrapper);
                if (paidTrack != null){
                    map.put(stackId, 1);
                }else {
                    map.put(stackId, 0);
                }
            });
        }


        return map;
    }
}
